# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
import pymongo
from scrapy import Request
from scrapy.exceptions import DropItem
from scrapy.pipelines.images import ImagesPipeline
import pymysql.cursors

class Douguo2Pipeline(object):
    def process_item(self, item, spider):
        return item


class MysqlPipeline1(object):
    def __init__(self):
        # 连接数据库
        self.connect = pymysql.connect(
            host='127.0.0.1',  # 数据库地址
            port=3306,  # 数据库端口
            db='test1',  # 数据库名
            user='root',  # 数据库用户名
            passwd='123',  # 数据库密码
            charset='utf8',  # 编码方式
            use_unicode=True)
        # 通过cursor执行增删查改
        self.cursor = self.connect.cursor()
    
    def process_item(self, item, spider):
        values = (
            item['level1'],
            item['level2'],
            item['name'],
            item['author'],
            item['intro'],
            item['materials'],
            item['steps'],
            item['tags'],
            item['url'],
            item['imgs_list'],)
        sql = 'insert into ' + 'douguo1'  + ' values (%s, %s, %s,%s, %s, %s,%s, %s, %s,%s)'  # 表格名称可能要更改
        self.cursor.execute(sql, values)
        # 提交sql语句
        self.connect.commit()
        return item  # 必须实现返回


class ImagePipeline(ImagesPipeline):
    def file_path(self, request, response=None, info=None):
        # 更改文件名
        url = request.url
        file_name = url.split('/')[-1]
        return file_name

    def item_completed(self, results, item, info):
        image_paths = [x['path'] for ok, x in results if ok]
        if not image_paths:
            raise DropItem('Image Download FAILD')
        return item

    def get_media_requests(self, item, info):
        for img in item['steps_imgs']:

            yield Request(img)


class MongoPipeline(object):
    def __init__(self, mongo_url, mongo_db):
        self.mongo_url = mongo_url
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        '''
        @classmethod  标识 依赖注入的方式
        该方法  用来从settings.py获取配置信息
        '''
        return cls(
            mongo_url=crawler.settings.get('MONGO_URL'),
            mongo_db=crawler.settings.get('MONGO_DB')
        )

    def open_spider(self, spider):
        """
        当开启spider时， 连接数据库，进行初始化操作
        """
        self.client = pymongo.MongoClient(self.mongo_url)
        self.db = self.client[self.mongo_db]

    def process_item(self, item, spider):
        name = item.__class__.__name__
        self.db[name].insert(dict(item))
        return item

    def close_spider(self, spider):
        """
        当关闭spider时， 关闭数据库连接
        """
        self.client.close()